package burubaka.controller.mnt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import net.arnx.jsonic.JSON;

import org.apache.commons.lang3.StringUtils;
import org.slim3.controller.Navigation;
import org.slim3.util.ApplicationMessage;

import burubaka.BurubakaConstants;
import burubaka.common.controller.Controller;
import burubaka.model.BetTemplate;
import burubaka.model.BetTemplateBody;
import burubaka.service.BetTemplateService;

public class DefaultBetTemplateController extends Controller {

	private static final Logger log = Logger.getLogger(DefaultBetTemplateController.class.getName());

	BetTemplateService betTemplateService = new BetTemplateService();

	@Override
	public Navigation init() throws Exception {

		BetTemplate betTemplate = betTemplateService.getDefaultBetTemplate();
		if (betTemplate == null) {
			return null;
		}
		List<BetTemplateBody> betTemplateBodyL = betTemplateService.findBetTemplateBodyByAncKey(betTemplate.getKey());
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("betTemplate", betTemplate);
		betTemplateService.setBetTemplateBody(resMap, betTemplateBodyL);
		String json = JSON.encode(resMap, true);
		log.fine(json);
		setJson(json);

		return null;
	}

	/**
	 * 登録
	 * 
	 * @param reqMap
	 * @return Navigation
	 * @throws Exception
	 */
	public Navigation regist() throws Exception {

		BetTemplate betTemplate = JSON.decode((String) reqMap.get("betTemplate"), BetTemplate.class);

		if (StringUtils.isEmpty(betTemplate.getName())) {
			setErrorJson("テンプレート名いれろや！");
			return null;
		}

		BetTemplateBody[] btb = JSON.decode((String) reqMap.get("betTemplateBody"), BetTemplateBody[].class);
		if (btb.length > BurubakaConstants.MAX_BET) {
			setErrorJson(ApplicationMessage.get(BurubakaConstants.MESSAGE_INFOMATIO_MAX_BET, BurubakaConstants.MAX_BET));
			return null;
		}
		List<BetTemplateBody> list = new ArrayList<BetTemplateBody>();
		long total = 0;
		for (BetTemplateBody betTemplateBody : btb) {
			long wager = betTemplateBody.getWager();
			total = total + wager;
			list.add(betTemplateBody);
		}

		if (total > 100) {
			setErrorJson(ApplicationMessage.get(BurubakaConstants.MESSAGE_INFOMATIO_TOTAL_AMAOUNT_OVER, null));
			return null;
		}

		BetTemplate old = betTemplateService.getDefaultBetTemplate();
		if (old != null) {
			betTemplate.setKey(old.getKey());
		}
		betTemplate.setDefaultFlag(BurubakaConstants.FLAG_ON);
		betTemplate = betTemplateService.regist(betTemplate, list);

		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put(BurubakaConstants.RESPONSEKEY_MESSAGE,
				ApplicationMessage.get(BurubakaConstants.MESSAGEKEY_REG_SUCCESS, null));
		setJson(JSON.encode(resMap, true));

		return null;
	}
}
